<template>
  <div>
    <Row :gutter="16">
      <!--      <Col span="6">-->
      <!--        <card icon="ios-options">-->
      <!--          <p slot="title" @click="FTreeClick" style="cursor: pointer">-->
      <!--            <Icon type="md-reorder"></Icon>-->
      <!--            {{firstdata.title}}-->
      <!--          </p>-->
      <!--          <CellGroup>-->
      <!--            <Tree :data="datalist" @on-select-change="choice"></Tree>-->
      <!--          </CellGroup>-->
      <!--        </card>-->
      <!--      </Col>-->
      <!--      <Col span="18">-->
      <div class="cardDiv">
        <card class="card" icon="ios-options">
          <p slot="title" @click="FTreeClick" style="cursor: pointer">
            <Icon type="md-reorder"></Icon>
            {{firstdata.title}}
          </p>
          <CellGroup>
            <Tree :data="datalist" @on-select-change="choice"></Tree>
          </CellGroup>
        </card>
      </div>
      <div class="search1">
        <Input class="search_input" v-model="searchText" placeholder="请输入住户名"/>
        <button class="search_btn" style="background-color: #235CA7;border-color: #235CA7" @click="searchHu">搜索</button>
      </div>
      <div :style="{height:offsetheight+'px'}">
        <el-amap vid="amap" class="amap-demo" :zoom="zoom" :center="center" :events="events">
          <!--中心标记点-->
          <el-amap-marker v-if="parseInt(this.current.level)!==6" vid="index_center" :position="center"
                          :events="total_events" :icon="markerImg" :offset="markerOffset"></el-amap-marker>
          <el-amap-marker v-if="searchCenterState===true" vid="index_center" :position="buildingCenter"
                          :events="buildingEvents" :icon="markerImg" :offset="markerOffset"></el-amap-marker>
          <!--              <el-amap-marker v-if="searchCenterState===true" vid="index_center" :position="center"></el-amap-marker>-->
          <!--楼标记点-->
          <el-amap-marker v-for="building in buildings" :key="building.id" :position="building.mapjson"
                          :events="building.events" :label="building.contentLabel" vid="index_buildings"></el-amap-marker>
          <!--楼号文字说明-->
<!--          <template v-for="(component,index) in componentMarker">-->
<!--            <el-amap-marker :key="'cm'+index" vid="component-marker" :position="component.position"-->
<!--                            :content-render="component.contentRender"></el-amap-marker>-->
<!--          </template>-->
          <!--商户标记点-->
          <template v-for="company in companies">
            <el-amap-marker v-if="company.mapjson!==undefined" :key="'c'+company.id" :position="company.mapjson"
                            :title="company.title" :icon="company.type" vid="index_companies"></el-amap-marker>
          </template>
          <!--统计弹窗-->
          <el-amap-info-window :visible="window.visible" :autoMove="false" :position="window.position"
                               :events="window.events" :content="window.content"></el-amap-info-window>
          <!-- 小组区域-->
          <el-amap-polygon v-for="(polygon, index2) in polygons" :key="index2" :vid="polygon"
                           :path="polygon.path" :fillColor="polygon.fillColor" :bubble="polygon.bubble"
                           :fillOpacity="polygon.fillOpacity"></el-amap-polygon>
        </el-amap>
      </div>
      <!--<div class="toolbar">
        位置: [{{ lng }}, {{ lat }}] <span v-if="this.address!=''">地址:</span> {{ address }}
      </div>-->
      <!--      </Col>-->
    </Row>
    <Modal :footer-hide="footerHide" v-model="modalHu" width="1300" title="门户信息">
      <Table border :loading="loading" :columns="columns" :data="datalist2"></Table>
      <div class="page_style">
        <div style="float: right; margin-left: 50px; height: 32px; line-height: 32px">共 {{ totalnum }} 条</div>
        <Page style="text-align: right" :total="totalnum" :current="currentPageNo" :page-size="currentPageSize"
              @on-change="change"/>
      </div>
    </Modal>
    <Modal :footer-hide="footerHide" v-model="modalBuild" width="1300" title="层户信息">
      <building v-if="showFloor" :fdata="floordata" :other="other_info"></building>
    </Modal>
  </div>
</template>

<script>
import {
  grid,
  auditmailfloor_getdownlist,
  auditmailcompany_uslist,
  auditmailfloor_getuserlist,
  auditmailfloor_getuserinfo
  // auditmailfloor_gethousenumx
  // auditmailfloor_getone
} from '@/api/eventlist'
import { transData } from '@/libs/tools'
import building from './building'

// const exampleComponents = {
//   props: ['text'],
//   template: `<div>text from  parent: {{text}}</div>`
// }

export default {
  name: 'grid',
  components: {
    building
  },
  data () {
    let self = this
    return {
      company_code: '',
      offsetheight: document.documentElement.clientHeight - 145,
      // offsetwidth: document.documentElement.clientWidth - 650,
      totalHuNum: 0, // 统计户数
      footerHide: true, // 模态框页脚隐藏
      searchText: '', // 搜索框输入内容
      loading: false, // 表格状态
      showFloor: false, // 层户组件初始值（刷新用）
      zoom: 9, // 缩放程度
      // 工具栏地址,经纬度
      address: '',
      lng: 0,
      lat: 0,
      // 统计弹窗
      window: {
        visible: false,
        position: [0, 0],
        content: '',
        events: {
          close () {
            self.window.visible = false
            // console.log('当前弹窗状态', self.window.visible)
          }
        }
      },
      // 标记点击统计事件
      total_events: {
        click (e) {
          self.searchHuNum()
          self.window.position = [e.lnglat.lng, e.lnglat.lat]
          // console.log(e.lnglat.lng, e.lnglat.lat)
          // console.log('事件内部的户数', self.totalHuNum)
        }
      },
      // 地图获取坐标事件
      events: {
        click (e) {
          let { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat
          // 这里通过高德 SDK 完成。
          let geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                self.address = result.regeocode.formattedAddress
                self.$nextTick()
              }
            }
          })
        }
      },
      // 中心坐标
      center: [123.4650090000, 41.6772870000],
      // 多边形
      polygons: [
        {
          bubble: true,
          fillOpacity: '0.2',
          fillColor: '#f77777',
          path: []
        }
      ],
      // 楼
      buildings: [
        {
          id: '',
          mapjson: [0, 0],
          title: '',
          events: {},
          contentLabel: {
            content: '测试',
            offset: [-5, 35]
          }
        }
      ],
      componentMarker: [],
      // 商户
      companies: [
        {
          id: '',
          mapjson: [0, 0],
          title: '',
          type: ''
        }
      ],
      columns: [
        { title: '序号', type: 'index', align: 'center' },
        { title: '姓名', key: 'name', align: 'center' },
        { title: '地址', key: 'address', align: 'center' },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            let temp = []
            temp.push(
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.info(params.row)
                  }
                }
              }, '详情')
            )
            return h('div', temp)
          }
        }
      ],
      datalist2: [], // 搜索后户表格数据
      totalnum: 0,
      currentPageNo: 1,
      currentPageSize: 10,
      datalist: [], // 树状图
      firstdata: [], // 头节点数据
      current: [], // 当前树节点信息
      modalBuild: false, // 层户信息模态框
      modalHu: false, // 层户信息模态框
      floordata: [], // 层户组件数据
      other_info: [], // 组件需要传入的其它信息
      buildingCenter: [0, 0], // 回显户所在楼坐标
      currentBuilding: '', // 当前详情楼id
      searchCenterState: false, // 用于判断详情回显楼坐标显示
      buildingEvents: {
        click (e) {
          // console.log('点击楼-》', e)
          // console.log(self.currentBuilding)
          self.modalBuild = true
          self.danyuan(self.currentBuilding)
        }
      },
      markerImg: './img/poi-marker-red.png',
      markerOffset: [-25, -45]
      // contentLabel: {
      //   content: '测试',
      //   offset: [-5, 35]
      // } // 楼标记说明
    }
  },
  methods: {
    init () {
      this.tree(arr => {
        this.datalist = arr[0].children
        this.firstdata = arr[0]
        this.current = arr[0]
        this.init_center()
        this.autoZoom()
        this.company(this.current.id)
        // console.log('当前级别', this.current.level)
      })
    },
    // 树
    tree (thing) {
      this.autoZoom()
      grid().then(res => {
        if (res.data.errcode === 0) {
          const arr = transData(res.data.data, 'id', 'pid', 'children')
          if (thing !== undefined) thing(arr)
          // console.log('格式化后的树', arr)
        } else {
          this.$Notice.error({
            title: '获取树形结构失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    // 商户标记
    company (param) {
      const data = {
        grid_id: param
      }
      auditmailcompany_uslist(data).then(res => {
        if (res.data.errcode === 0) {
          this.companies = []
          res.data.data.forEach(element => {
            if (element.mapjson !== undefined) {
              element.mapjson = element.mapjson.split(',')
            }
          })
          this.companies = res.data.data
          this.autoPic(this.companies)
          // console.log('转换后商户信息：', this.companies)
        } else {
          this.$Notice.error({
            title: '获取商户标记失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    // 楼
    building (param) {
      const data = {
        pid: param,
        level: '102'
      }
      auditmailfloor_getdownlist(data).then(res => {
        if (res.data.errcode === 0) {
          if (res.data.data.length !== 0) {
            const newArr = transData(res.data.data, 'id', 'pid', 'list')
            // console.log('该小组返回信息', newArr)
            let arr = []
            newArr.forEach(element => {
              if (element.mapjson !== undefined) {
                element.mapjson = element.mapjson.split(',')
                let obj = {
                  ...element,
                  events: {
                    click: () => {
                      this.clickMaker(element)
                    }
                  },
                  contentLabel: {
                    content: element.title,
                    offset: [-5, 35]
                  }
                }
                arr.push(obj)
              }
            })
            this.buildings = arr
            // this.buildings.forEach((item, index) => {
            //   this.componentMarker.push({
            //     position: item.mapjson,
            //     contentRender: (h) => h('div', {
            //       style: {
            //         textAlign: 'center',
            //         // backgroundColor: 'transparent',
            //         borderRadius: '4px',
            //         backgroundColor: 'rgba(255, 255, 255, 0.7)',
            //         marginTop: '29px',
            //         marginLeft: '-15px',
            //         width: '50px',
            //         height: '18px'
            //       }
            //     }, [item.title])
            //   })
            // })
            // console.log('该小组楼信息', this.buildings)
          } else {
            this.$Message.error('此小组暂无楼信息')
          }
        } else {
          this.$Notice.error({
            title: '获取楼组信息失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    // 层户信息
    danyuan (param) {
      // console.log('层户信息：', param)
      const data = {
        pid: param,
        level: '102'
      }
      this.showFloor = false
      // console.log('传入', param)
      auditmailfloor_getdownlist(data).then(res => {
        this.floordata = []
        // console.log('楼原返回数据：', res.data.data)
        const newArr = transData(res.data.data, 'id', 'pid', 'list')
        this.floordata = newArr
        // console.log('转换后', newArr)
        if (res.data.errcode === 0) {
          if (res.data.data.length !== 0) {
            this.showFloor = true
          }
        } else {
          this.$Notice.error({
            title: '获取层户信息失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    // 初始化中心点(非小组mapjson)
    init_center () {
      let current_center = this.current.mapjson
      let str = current_center.split(',')
      this.center = []
      this.center.push(str[0])
      this.center.push(str[1])
      this.lng = str[0]
      this.lat = str[1]
    },
    // 树节点点击事件
    choice (data, res) {
      this.current = res
      this.buildings = []
      this.componentMarker = []
      console.log('当前级别', this.current.level)
      console.log('当前id:', this.current.id)
      console.log(this.current)
      this.company_code = this.current.company_code
      if (parseInt(this.current.level) !== 6) {
        this.init_center()
        this.polygons[0].path = []
        this.company(this.current.id)
      } else {
        this.companies = []
        this.other_info = []
        // console.log('mapjson:', this.current.mapjson)
        this.polygons[0].path = JSON.parse(this.current.mapjson)
        this.center = this.autoCenter(this.current.mapjson)
        this.building(this.current.id)
      }
      this.searchCenterState = false
      this.window.visible = false
      this.autoZoom()
      // console.log('当前节点', this.current)
      // console.log('当前中心点', this.center)
    },
    // 树头节点点击事件
    FTreeClick () {
      this.current = this.firstdata
      this.init_center()
      this.polygons[0].path = []
      this.buildings = []
      this.componentMarker = []
      this.company(this.current.id)
      this.autoZoom()
      this.searchCenterState = false
      this.window.visible = false
      // console.log('当前节点', this.current)
      // console.log('当前中心点', this.center)
    },
    // 根据级别调整zoom
    autoZoom () {
      if (parseInt(this.current.level) === 6) {
        this.zoom = 17 // 小组
      } else if (parseInt(this.current.level) === 5) {
        this.zoom = 16 // 小区
      } else if (parseInt(this.current.level) === 4) {
        this.zoom = 15 // 社区
      } else if (parseInt(this.current.level) === 3) {
        this.zoom = 13 // 街道
      } else if (parseInt(this.current.level) === 2) {
        this.zoom = 12 // 区
      }
    },
    // 根据多边形自动取中心点
    autoCenter (map) {
      let path = JSON.parse(map)
      let total_lng = 0.0
      let total_lat = 0.0
      path.forEach(arr => {
        total_lng += arr[0]
        total_lat += arr[1]
      })
      let newlng = total_lng / path.length
      let newlat = total_lat / path.length
      let newCenter = [newlng, newlat]
      return newCenter
    },
    // 根据type转换成图标路径
    autoPic (param) {
      param.forEach(e => {
        if (parseInt(e.type) === 1) {
          e.type = './img/bank.png' // 银行
        } else if (parseInt(e.type) === 2) {
          e.type = './img/public_institution.png' // 事业单位
        } else if (parseInt(e.type) === 3) {
          e.type = './img/business.png' // 商户
        } else if (parseInt(e.type) === 4) {
          e.type = './img/company.png' // 公司
        } else if (parseInt(e.type) === 5) {
          e.type = './img/institution.png' // 单位
        } else if (parseInt(e.type) === 6) {
          e.type = './img/park.png' // 公园
        } else if (parseInt(e.type) === 7) {
          e.type = './img/square.png' // 广场
        } else {
          e.type = '' // 无
        }
      })
    },
    // buiding中点击事件
    clickMaker (data) {
      // console.log(data)
      if (data.list !== undefined) {
        this.modalBuild = true
        // this.default_danyuan(data.id)
        this.danyuan(data.id)
      } else {
        this.modalBuild = false
        this.$Message.error('此楼暂无层户信息')
      }
    },
    // 查询户的搜索
    searchHu () {
      this.loading = true
      // console.log('查询户搜索内容', this.searchText)
      const data = {
        name: this.searchText,
        pageNo: this.currentPageNo,
        pageSize: this.currentPageSize,
        company_code: this.company_code
      }
      console.log(data)
      auditmailfloor_getuserlist(data).then(res => {
        if (res.data.errcode === 0) {
          this.modalHu = true
          this.datalist2 = res.data.data.results
          this.totalnum = res.data.data.totalRecord
          this.loading = false
        } else {
          this.$Notice.error({
            title: '获取搜索结果失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    // 查询后的详情
    info (item) {
      // console.log(item)
      const data = {
        id: item.final_id
      }
      auditmailfloor_getuserinfo(data).then(res => {
        if (res.data.errcode === 0) {
          // console.log(res.data.data.ids)
          if (res.data.data.ids !== undefined) {
            let str = res.data.data.ids
            let newstr = str.split(',')
            console.log(newstr)
            let arr = newstr.slice(1)
            // console.log(newstr[0], '==', newstr[1], '==', newstr[2], '==', newstr[3], '==')
            this.modalHu = false
            this.polygons[0].path = []
            this.buildings = []
            this.companies = []
            this.searchCenterState = true
            // let map = item.mapjson.split(',')
            // this.center = map
            // this.buildingCenter = map
            this.zoom = 17
            // console.log(map)
            this.modalBuild = true
            this.danyuan(newstr[0])
            this.currentBuilding = newstr[0]
            arr.push(item.id)
            this.other_info = arr
            console.log('传值信息', this.other_info)
          }
        } else {
          this.$Notice.error({
            title: '详情获取失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    // 户表格分页改变事件
    change (pageNo) {
      this.currentPageNo = pageNo
      this.searchHu()
    },
    // 查询户数
    async searchHuNum () {
      // console.log('当前id', this.current.id)
      const data = {
        id: this.current.id
      }
      let res = await auditmailfloor_gethousenum(data)
      if (res.data.errcode === 0) {
        // console.log('当前总数', res.data.data.num)
        this.totalHuNum = res.data.data.num
        this.window.visible = true
        this.window.content = '共计' + this.totalHuNum + '户'
      } else {
        this.$Notice.error({
          title: '户数获取失败',
          desc: res.data.errmsg
        })
      }
    }
  },
  mounted () {
    this.init()
  }
}
</script>

<style scoped>
  /*.amap-page-container {*/
  /*  background-color: whitesmoke;*/
  /*  float: right;*/
  /*}*/

  /deep/ .amap-marker-label {
    border-radius: 4px;
    background: rgba(255, 255, 255, 0.93);
    border: 1px solid rgba(52, 144, 245, 0.9);
  }

  .cardDiv {
    width: 200px;
    position: absolute;
    top: 30px;
    left: 20px;
    z-index: 1000;
  }

  .card {
    background:rgba(255,255,255,0.93);
    height:500px;
    overflow: auto;
  }

  ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
    background-color: rgba(255,255,255,0.93);
  }

  ::-webkit-scrollbar-thumb {
    border-radius:5px;
    -webkit-box-shadow: inset 0 0 6px rgba(250, 250, 250, .3);
    background-color: rgba(220,220,220,0.93);
  }

  ::-webkit-scrollbar-corner {
    background-color: rgba(255,255,255,0.93);
  }

  .toolbar {
    text-align: center;
    margin-top: 10px;
  }

  .search1 {
    width: 200px;
    position: absolute;
    top: 30px;
    left: 250px;
    z-index: 1000;
  }

  .search_input {
    display: inline-block;
    width: 160px;
  }

  .search_input /deep/ input {
    border-top-right-radius: 0px !important;
    border-bottom-right-radius: 0px !important;
    background-color: rgba(255,255,255,0.93) !important;
  }

  .search_btn {
    display: inline-block;
    width: 40px;
    height: 32px;
    cursor: pointer;
    background-color: rgba(45,140,240,0.93);
    color: #fff;
    z-index: 1001;
    font-size: 12px;
    border: 1px solid transparent;
    transition: border 0.2s ease-in-out, background 0.2s ease-in-out, box-shadow 0.2s ease-in-out, -webkit-box-shadow 0.2s ease-in-out;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    vertical-align: middle;
    line-height: normal;
    position: absolute;
    left: 160px;
  }

  .search_btn:hover {
    background: #57a3f3 !important;
    border-color: #57a3f3 !important;
  }

  .search_btn:active {
    background: #2b85e4 !important;
    border-color: #2b85e4 !important;
  }

  .page_style {
    margin-top: 10px;
    position: relative;
  }
</style>
